package com.weibo.click;

import java.awt.AWTException;
import java.awt.Robot;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/*处理163和QQ申请的click问题*/
public class Mail163ClickServer {
	private int port;
	public Mail163ClickServer(int port) {
		this.port = port;
	}

	public void start() {
		try {
		    InetSocketAddress address = new InetSocketAddress("127.0.0.1", port);
			HttpServer server = HttpServer.create(address, 0);
			server.createContext("/", new HttpHandler() {
				public void handle(HttpExchange he) {
					try {
						InputStream input_stream = he.getRequestBody();
  				        BufferedReader reader = new BufferedReader(
								new InputStreamReader(input_stream));
						StringBuilder str_builder = new StringBuilder();

						String line = null;
						while ((line = reader.readLine()) != null) {
							str_builder.append(line);
						}
						String qStr=str_builder.toString();
						QueryString qs = new QueryString(qStr);
						if(qStr.contains("msg")){
						   handleMsg(qs);
						}
						// 登录，
						String ret = "OK";
						he.sendResponseHeaders(200,ret.getBytes("utf-8").length);
						OutputStream os = he.getResponseBody();
						os.write(ret.getBytes());
						os.close();
					} catch (Exception e) {
						System.out.println("handle Exception");
						//e.printStackTrace();
					}

				}

				/**
				 * @param qs
				 */
				private void handleMsg(QueryString qs) {
					try {
						int xPos = Integer.parseInt(qs.getParameter("xPos"));
						int yPos = Integer.parseInt(qs.getParameter("yPos"));
						String msg = qs.getParameter("msg");
						ClipboardUtils clip=new ClipboardUtils();
						clip.mouseMoveAndClick(xPos,yPos);
						clip.type(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
			});
			server.start();
			System.out.println("Monitoring " + port + " port");
		} catch (Exception e) {
			System.out.println("localHttpLisener Exception");
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {
		new Mail163ClickServer(19988).start();
	}

}
